package org.lyh.gift.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.lyh.gift.domain.AlicloudOSSProperties;
import org.lyh.gift.pojo.dto.PhoneCodeDto;
import org.lyh.gift.service.ICommonService;
import org.lyh.gift.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/commons")
public class CommonController {

    @Value("${fastdfs.prefix}")
    private String prefix;

    @Autowired
    private ICommonService commonService;
    @Autowired
    private AlicloudOSSProperties properties;

//    @PostMapping("/upload")
//    public AjaxResult fileUpload(MultipartFile file) throws IOException {
//
//        //从file里面获取后缀名
//        String originalFilename = file.getOriginalFilename();//获取文件的原始名字
//        //从原始名字里面获取后缀名  1. 分隔截取  2.在文件上传工具包里面有一个获取后缀名的方法
//        String extName = FilenameUtils.getExtension(originalFilename);
//
//        String upload = FastdfsUtil.upload(file.getBytes(), extName);
//        //返回当前文件的访问路径
//        return AjaxResult.me().setSuccess(true).setMessage(prefix + upload);
//    }
    //图片上传
@GetMapping("/sign")
protected AjaxResult doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // 填写Host名称，格式为https://bucketname.endpoint。
    // host的格式为 bucketname.endpoint
    String host = "https://" + properties.getBucket() + "." + properties.getEndpoint();
    // 设置上传回调URL，即回调服务器地址，用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后，把文件上传信息通过此回调URL发送给应用服务器。
    String callbackUrl = "https://192.168.0.0:8888";
    // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
    String dir = "img";

    // 创建OSSClient实例。
    OSS ossClient = new OSSClientBuilder().build(properties.getEndpoint(), properties.getAccess(),properties.getSecret());
    try {
        long expireTime = 30;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

        String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
        byte[] binaryData = postPolicy.getBytes("utf-8");
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = ossClient.calculatePostSignature(postPolicy);

        Map<String, String> respMap = new LinkedHashMap<String, String>();
        respMap.put("accessid", properties.getAccess());
        respMap.put("policy", encodedPolicy);
        respMap.put("signature", postSignature);
        respMap.put("dir", dir);
        respMap.put("host", host);
        respMap.put("expire", String.valueOf(expireEndTime / 1000));
        // respMap.put("expire", formatISO8601Date(expiration));
        return AjaxResult.me().setResultObj(respMap);
    } catch (Exception e) {
        // Assert.fail(e.getMessage());
        System.out.println(e.getMessage());
        return AjaxResult.me().setSuccess(false).setMessage("上传失败");
    } finally {
        ossClient.shutdown();
    }
}
    @GetMapping("/imgCode/{uuid}")
    public AjaxResult imgCode(@PathVariable("uuid") String uuid){
        String code = commonService.createImgCode(uuid);

        return AjaxResult.me().setResultObj(code);
    }
    @PostMapping("/phoneCode")
    public AjaxResult phoneCode(@RequestBody PhoneCodeDto phoneCodeDto){
        commonService.sendPhoneCode(phoneCodeDto);
        return AjaxResult.me();
    }

}
